package com.dbq.fast.business.main.dialog;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.me.api.AccountManagerAPI;
import com.dbq.fast.business.me.help.CountDownUtil;
import com.dbq.fast.common.manager.DatabaseManager;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.util.WindowToastUtils;
import com.yiba.vpn.utils.Constants;
import com.yiba.vpn.utils.RxBus;

import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**绑定邮箱**/
public class BindEmailDialog extends android.support.v4.app.DialogFragment {

    private static final String DIALOG_TAG = "bindemaildialog";
    private Unbinder unbinder;
    private CountDownUtil countDownUtil;
    private static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[_-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    @BindView(R.id.ed_email)
    EditText ed_email;
    @BindView(R.id.ed_code)
    EditText ed_code;
    @BindView(R.id.tv_code)
    TextView tv_code;

    @BindView(R.id.line_code)
    View line_code;
    @BindView(R.id.line_mail)
    View line_mail;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0x00ffffff));
        getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_bind_email, container, true);
        unbinder = ButterKnife.bind(this, view);
        ed_email.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                line_code.setBackgroundColor(getResources().getColor(R.color.gray_dfdf));
                line_mail.setBackgroundColor(getResources().getColor(R.color.colorAccent));
            } else {
                line_code.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                line_mail.setBackgroundColor(getResources().getColor(R.color.gray_dfdf));
            }
        });
        ed_code.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                line_code.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                line_mail.setBackgroundColor(getResources().getColor(R.color.gray_dfdf));
            } else {
                line_code.setBackgroundColor(getResources().getColor(R.color.gray_dfdf));
                line_mail.setBackgroundColor(getResources().getColor(R.color.colorAccent));
            }
        });
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public static BindEmailDialog newInstance() {
        return new BindEmailDialog();
    }

    public static BindEmailDialog show(FragmentManager fragmentManager) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (fragmentManager.findFragmentByTag(DIALOG_TAG) instanceof BindEmailDialog) {
            BindEmailDialog prev = (BindEmailDialog) fragmentManager.findFragmentByTag(DIALOG_TAG);
            if (prev != null) {
                if (prev.isVisible()) {
                    prev.dismiss();
                }
                ft.remove(prev);
            }
            ft.addToBackStack(null);
        }
        BindEmailDialog bindEmailDialog = BindEmailDialog.newInstance();
        try {
            bindEmailDialog.show(ft, DIALOG_TAG);
        }catch (Exception e){}
        return bindEmailDialog;
    }


    @OnClick({R.id.tv_code, R.id.bind})
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_code:
                if(checkCode()){
                    countDownUtil = new CountDownUtil(tv_code)
                            .setCountDownMillis(60_000L)//倒计时60000ms
                            .setCountDownColor(android.R.color.white, R.color.white)//不同状态字体颜色
                            .setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    getCode();
                                }
                            })
                            .start();
                    getCode();
                    ed_code.requestFocus();
                }
                break;
            case R.id.bind:
                if(checkAll()){
                    bindEmail();
                }
                break;
        }
    }
    /**绑定邮箱**/
    private void bindEmail() {
        AccountManagerAPI.bindEmail(new RemoteApiCallBack<String>() {
            @Override
            public void onFail(int status, String message) {
                WindowToastUtils.showShort(App.getContext(), message);
            }

            @Override
            public void onSuccess(String s) {
                //刷新界面
                CustomProfile  customProfile = DatabaseManager.getInstance().queryProfile();
                customProfile.setEmail(ed_email.getText().toString());
                DatabaseManager.getInstance().saveProfile(customProfile);
                RxBus.get().post(Constants.RXBUS_BIND_EAMIL, Constants.RXBUS_BIND_EAMIL);
                dismiss();
            }
        },ed_email.getText().toString(),ed_code.getText().toString());
    }

    /**获取验证码**/
    private void getCode() {
        AccountManagerAPI.requestEmailVerifiCode(new RemoteApiCallBack<String>() {
            @Override
            public void onFail(int status, String message) {
                WindowToastUtils.showShort(App.getContext(), "获取验证码失败,请稍后再试");

            }

            @Override
            public void onSuccess(String s) {

            }
        },ed_email.getText().toString());
    }
    /**检测邮箱**/
    private boolean checkCode() {
        if(ed_email!=null) {
            if (TextUtils.isEmpty(ed_email.getText().toString())) {
                WindowToastUtils.showShort(App.getContext(), "请输入邮箱");
                return false;
            } else if (!Pattern.matches(REGEX_EMAIL,ed_email.getText().toString())) {
                WindowToastUtils.showShort(App.getContext(), "邮箱格式不对");
                return false;
            }else {
                return true;
            }
        }
        return false;
    }

    /**检查邮箱和验证码**/
    private boolean checkAll() {
        if(ed_email!=null&&ed_code!=null) {
            if (TextUtils.isEmpty(ed_email.getText().toString())) {
                WindowToastUtils.showShort(App.getContext(), "请输入邮箱");
                return false;
            } else if (!Pattern.matches(REGEX_EMAIL,ed_email.getText().toString())) {
                WindowToastUtils.showShort(App.getContext(), "邮箱格式不对");
                return false;
            }else if (TextUtils.isEmpty(ed_code.getText().toString())) {
                WindowToastUtils.showShort(App.getContext(), "请输入验证码");
                return false;
            }else {
                return true;
            }
        }
        return false;
    }




}
